import axios from 'axios'
import Messages from '@/api/codes'
import {ElMessage as Message} from 'element-plus'
import router from "@/router/index.js";

// 创建axios实例
const http = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL, // baseURL: 'http://127.0.0.1:8080',
	timeout: 50000,
})

// 请求缓存
const requestCache = new Map()

// 错误处理函数
function handleError(response) {
	const message = response.msg || Messages[response.code] || '未知错误'
	if (response.code === 200) {
		return response  // 返回成功响应
	} else {
		Message.error(message) // 显示错误消息
		return response // 返回错误对象
	}
}

// 请求拦截器
http.interceptors.request.use((config) => {
	const {url, method, data} = config
	const requestKey = `${url}-${method}-${JSON.stringify(data)}`
	const now = Date.now()
	if (requestCache.has(requestKey) && now - requestCache.get(requestKey) < 200) {
		return Promise.reject(new Error('Too many requests'))
	}
	requestCache.set(requestKey, now)
	// 检查白名单
	const whiteList = ['/user/login', '/user/register'] // 不需要token的API
	if (!whiteList.includes(config.url)) {
		const token = localStorage.getItem('WFITToken') // 假设token存储在localStorage
		if (token) {
			config.headers['token'] = token
		}
	}
	return config
}, (error) => {
	return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use((response) => {
	const contentType = response.headers['content-type'] || '';
	// 如果是 JSON 类型响应，继续处理 code
	if (contentType.includes('application/json')) {
		const res = response.data;
		if (res.code === 401) {
			Message.error('登录过期，请重新登录');
			localStorage.removeItem('WFITToken');
			localStorage.removeItem('WFITInfo');
			router.push('/login');
			return res;
		}
		if (res.code !== 200 && res.code in Messages) {
			return handleError(res) || res;
		}
	} else {
		return response;
	}
	// 对于文件流等非 JSON 类型响应，直接返回原始数据
	return response.data;
}, (error) => {
	console.log(error.response)
	return handleError(error.response?.status || 500)
})

export default http
